package com.maistars.spider.common.util;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

public class FileUtil {

    /**
     * @param str      待写入文件的字符串
     * @param filePath 文件路径
     * @return 写入是否成功
     * @Description 该方法实现将字符串写入指定的文本中
     */
    public static boolean writeStrToFile(String str, String filePath) {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(filePath);
            fileWriter.write(str);
            fileWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    public static InputStream getResourceFileInputStream(String path){
        ClassPathResource resource = new ClassPathResource(path);
        InputStream fis = null;
        try {
            fis = resource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            return null;
        }
        return fis;
    }

    public static File getResourceFile(String path){
        ClassPathResource resource = new ClassPathResource(path);
        File file = null;
        try {
            file  = resource.getFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static String readFileToString(String fileName) {
        try {
            File jsonFile = new File(fileName);
            return FileUtils.readFileToString(jsonFile, Charsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String urlToFileName(String url){
        url= StringUtils.replace(url,"http","_");
        url=StringUtils.replace(url,".htm","");
        url=StringUtils.replace(url,":","_");
        url=StringUtils.replace(url,"/","_");
        url=StringUtils.replace(url,"\\","_");
        url=StringUtils.replace(url,".","_");
        return url;
    }

}